﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DingApi.Models;
using System.Data;

using System.Web;
using Dingding.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

/*
 * 由于调拨通知没有指定：包装方式；
 * 原二维码也仅能管理到批次，没法管理到包装方式；
 * 
 * 2023年11月28日与徐志强确认，老的标签暂时不暂时不考虑；
 * 次调拨仅支持有材料编码的，且材料编码的仅能通过手持挑拨实现【若通过电脑是不行的serve不同，也具有可操作性，电脑端很难道具体材料，只能到批号；】
 
   
     */

namespace DingApi.Controllers
{
    [RoutePrefix("api/Ym03dbi")]
    public class Ym03dbiController : ApiController
    {

        /// <summary>
        /// /调拨通知单；要求，调出有明确库区、调入有明确库区、产品有规格明细；
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PostYm03dbi_Bill_inq")]
        public System.Data.DataSet PostYm03dbi_Bill_inq([FromBody]  JObject obj)
        {
            //系统信息；
            EI.EIInfo outBlock = new EI.EIInfo();
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");



            EI.EIInfo inBlock = new EI.EIInfo();

          

            string MOVE_STOCK_APPLY_NO = obj["BILL_OF_LADING_NO"] == null ? " " : obj["BILL_OF_LADING_NO"].ToString();


            /*  对应画面；MM0042BR
             *  对应表 tmm0031 主表；TMM0033 子表 */

           

            string sql_str0 = "select * from  tmm0031  ";
            sql_str0 += "      where   MOVE_STOCK_APPLY_NO =  '" + MOVE_STOCK_APPLY_NO + "' ";


            EI.EIInfo codeInfo1 = EF.Utility.ExecQuery(sql_str0);
            if (codeInfo1.Tables[0].Rows.Count < 1)
            {
                outBlock.Tables["SYS"].Rows.Add(-1, "错误,申请单号[" + MOVE_STOCK_APPLY_NO + "]不存在！");               
                return outBlock;
            }
            if (codeInfo1.Tables[0].Rows[0]["BILL_STATUS"].ToString().Trim() != "30" 
                && codeInfo1.Tables[0].Rows[0]["BILL_STATUS"].ToString().Trim() != "40")
            {
                outBlock.Tables["SYS"].Rows.Add(-1, "错误,申请单号[" + MOVE_STOCK_APPLY_NO + "]状态不对，请确认调拨出库单是否确认！");
                return outBlock;
            }

            //判断该调拨入库申请单（挑拨出库单）是否已经被引用

            sql_str0 = " select MOVE_STOCK_NO from tmm0034    ";
            sql_str0 += "      where   MOVE_STOCK_APPLY_NO =  '" + MOVE_STOCK_APPLY_NO + "' ";


            EI.EIInfo codeInfo_Temp = EF.Utility.ExecQuery(sql_str0);
            if (codeInfo_Temp.Tables[0].Rows.Count !=0 )
            {
                outBlock.Tables["SYS"].Rows.Add(-1
                    , "错误,调拨申请单号[" 
                    + MOVE_STOCK_APPLY_NO + "]已经入库了，不可重复入库，调拨入库单号为["
                    + codeInfo_Temp.Tables[0].Rows[0]["MOVE_STOCK_NO"].ToString() + "]");
                return outBlock;
            }

             






         string sql2= " SELECT  ' ' PACK_MODE_NAME, t.*   FROM TMM0033  t "
                        + " WHERE   IOSTOCK_BILL_NO     =  '" + MOVE_STOCK_APPLY_NO + "' ";

            //明细数据； codeInfo2
            EI.EIInfo codeInfo2 = EF.Utility.ExecQuery(sql2);
            if (codeInfo2.Tables[0].Rows.Count < 1)
            {
                outBlock.Tables["SYS"].Rows.Add(-1, "错误,申请单号[" + MOVE_STOCK_APPLY_NO + "]没有出库明细数据！");
                return outBlock;
            }


            //质量等级；
            string sql_str1 = "    select code,code_desc_1_content from tep0002   where code_class = 'QMQK' "
                            + "   and code_desc_2_content like '%N%'   ";
            //仓库代码转换
            EI.EIInfo outBlock_TEMP = EF.Utility.ExecQuery(sql_str1); //QUAL_GRADE_CODE


            //包装方式名称
            sql_str1 = "    select  PACK_MODE_CODE  CODE  ,   PACK_MODE_NAME CODE_DESC_1_CONTENT	 from   tsiqmw0	";

            EI.EIInfo outBlock_TEMP2 = EF.Utility.ExecQuery(sql_str1); //PACK_MODE_CODE


            DataTable dtTemp = null;


            for (int i = codeInfo2.Tables[0].Rows.Count - 1; i >= 0; i--)
            {

                codeInfo2.Tables[0].Rows[i]["IOSTOCK_APPLY_NO"]     = codeInfo2.Tables[0].Rows[i]["IOSTOCK_BILL_NO"];
                codeInfo2.Tables[0].Rows[i]["IOSTOCK_APPLY_SUB_NO"] = codeInfo2.Tables[0].Rows[i]["IOSTOCK_SUB_NO"];

                codeInfo2.Tables[0].Rows[i]["ACCOMPLISH_FLAG"] = " ";//确保与前台一直；

                string qual_grade_code = codeInfo2.Tables[0].Rows[i]["QUAL_GRADE_CODE"].ToString().Trim();
                if (qual_grade_code.Trim() != "")
                {
                    if (outBlock_TEMP.Tables[0].Select("CODE  = '" + qual_grade_code + "'").Count<DataRow>() == 1)
                    {
                        dtTemp = outBlock_TEMP.Tables[0].Select("CODE  = '" + qual_grade_code + "'").CopyToDataTable<DataRow>();
                        codeInfo2.Tables[0].Rows[i]["QUAL_GRADE_DESC"] = dtTemp.Rows[0]["CODE_DESC_1_CONTENT"];
                    }
                }
                string pack_mode_code = codeInfo2.Tables[0].Rows[i]["PACK_MODE_CODE"].ToString().Trim();
                if (pack_mode_code.Trim() != "")
                {
                    if (outBlock_TEMP2.Tables[0].Select("CODE  = '" + pack_mode_code + "'").Count<DataRow>() == 1)
                    {
                        dtTemp = outBlock_TEMP2.Tables[0].Select("CODE  = '" + pack_mode_code + "'").CopyToDataTable<DataRow>();
                        codeInfo2.Tables[0].Rows[i]["PACK_MODE_NAME"] = dtTemp.Rows[0]["CODE_DESC_1_CONTENT"];
                    }
                }



                //UpDownFileFtpController ctr = new UpDownFileFtpController();
                //string mat_no = outBlock.Tables[0].Rows[i]["MAT_NO"].ToString();
                //int files_num = ctr.PostGetFilesNum("DCXA", mat_no, "");
                //outBlock.Tables[0].Rows[i]["FIELD_N1"] = files_num;



            }












            //仅指定调出仓库，没有指定库区；
            sql2 =   " SELECT  STOCK_NO CODE , STOCK_NAME CODE_DESC_1_CONTENT   FROM TSIMM01 WHERE" 
                    +   " STOCK_NO = '" + codeInfo1.Tables[0].Rows[0]["OLD_STOCK_NO"].ToString().Trim() + "'"
                    ;

             EI.EIInfo codeInfo3 = EF.Utility.ExecQuery(sql2);
            codeInfo3.Tables[0].TableName = "OLD_STOCK_NO";


            EI.EIInfo codeInfo4 = new EI.EIInfo();
            String[] pInfos = codeInfo1.Tables[0].Rows[0]["NEW_STOCK_NO"].ToString().Trim().Replace(":", ",").Split(',');

            codeInfo4.Tables[0].Columns.Add("CODE");
            codeInfo4.Tables[0].Columns.Add("CODE_DESC_1_CONTENT");

            for (int iCyc = 0; iCyc < pInfos.Length / 2; iCyc++)
            {
                codeInfo4.Tables[0].Rows.Add();
                codeInfo4.Tables[0].Rows[iCyc]["CODE"] = pInfos[iCyc * 2];
                codeInfo4.Tables[0].Rows[iCyc]["CODE_DESC_1_CONTENT"] = pInfos[iCyc * 2 + 1];
            }
            codeInfo4.Tables[0].TableName = "NEW_STOCK_NO";

            



            codeInfo1.Tables[0].TableName = "MAIN";
            outBlock.Tables.Add(codeInfo1.Tables[0].Copy());

            codeInfo2.Tables[0].TableName = "GRID";
            outBlock.Tables.Add(codeInfo2.Tables[0].Copy());

            outBlock.Tables.Add(codeInfo3.Tables[0].Copy());
            outBlock.Tables.Add(codeInfo4.Tables[0].Copy());





            outBlock.Tables["SYS"].Rows.Add(0, "申请单查询成功");            
            return outBlock;


        }


        /// <summary>
        /// 获取提单子项对应的材料库位分布【待补充】
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PostYm03dbi_Bill_Sub_inq")]
        public System.Data.DataSet PostYm03dbi_Bill_Sub_inq([FromBody]  JObject obj)
        {
            //系统信息；
            EI.EIInfo outBlock = new EI.EIInfo();
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");





            // MAT_NO，PROD_LOT_NO 必须有一个值；钉钉前端校验；
            string BILL_OF_LADING_SUB_NO = obj["IOSTOCK_SUB_NO"] == null ? "" : obj["IOSTOCK_SUB_NO"].ToString();
            string STOCK_NO = obj["STOCK_NO"] == null ? "" : obj["STOCK_NO"].ToString();




            string sql_temp = "";

            EI.EIInfo Block_TSOSD03 = new EI.EIInfo();

             

          sql_temp = "    select  LOCATION_NO, count(*) NUM "
                        + "   from TPMMM02N ta, TMM0033 tb   "
                        + "     WHERE    tb.IOSTOCK_SUB_NO = '" + BILL_OF_LADING_SUB_NO + "'"
                        + "      and  ta.stock_no = '" + STOCK_NO + "'"
                        + "     and tb.PROD_CODE = ta.PROD_CODE    "
                        + "     and tb.sg_sign = ta.sg_sign "
                        + "     and tb.mat_spec_desc = ta.mat_spec_desc "
                        + "     and tb.PACK_MODE_CODE = ta.PACK_MODE_CODE "
                        + "     group by LOCATION_NO   "
                        + "     order by  count(*)  "
                        ;
            Block_TSOSD03 = EF.Utility.ExecQuery(sql_temp);
            if (Block_TSOSD03.Tables[0].Rows.Count < 1)
            {
                //outBlock.Tables["SYS"].Rows.Add(-1, "该提单子项[" + BILL_OF_LADING_SUB_NO + "]无有效库存！");
                //return outBlock;

                Block_TSOSD03.Tables[0].Rows.Add("无", "0");


            }



            //多余1个仓库
            Block_TSOSD03.Tables[0].TableName = "LOCATION_NO";
            outBlock.Tables.Add(Block_TSOSD03.Tables[0].Copy());

 




            outBlock.Tables["SYS"].Rows.Add(0, "");
            return outBlock;

        }




        //调拨出库保存【新增操作、修改操作】
        [HttpPost]
        [Route("PostYm03dbi_save")]       
        public System.Data.DataSet PostYm03dbi_save([FromBody]  JObject obj)
        {

            //系统信息；
            EI.EIInfo outBlock = new EI.EIInfo();
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");





            // 申请单号；
            string MOVE_STOCK_APPLY_NO = obj["BILL_OF_LADING_NO"] == null ? "" : obj["BILL_OF_LADING_NO"].ToString();

            //调拨出库单号
            string MOVE_STOCK_NO = obj["MOVE_STOCK_NO"] == null ? " " : obj["MOVE_STOCK_NO"].ToString();

          



            string OLD_STOCK_NO = obj["OLD_STOCK_NO"] == null ? "" : obj["OLD_STOCK_NO"].ToString();
            string NEW_STOCK_NO = obj["NEW_STOCK_NO"] == null ? "" : obj["NEW_STOCK_NO"].ToString();

            string VEHICLE_NO = obj["VEHICLE_NO"] == null ? "" : obj["VEHICLE_NO"].ToString();
             
            string USERID = obj["USERID"] == null ? " " : obj["USERID"].ToString();
            string USERNAME = obj["USERNAME"] == null ? " " : obj["USERNAME"].ToString();
            string FORMNAME = obj["FORMNAME"] == null ? " " : obj["FORMNAME"].ToString();
            string PRO_TYPE = obj["PRO_TYPE"] == null ? " " : obj["PRO_TYPE"].ToString();


            DataTable table_rec = JsonConvert.DeserializeObject<DataTable>(obj["table_rec"].ToString(), new DingApi.ReadAheadDataTableConverter());;

             


            EI.EIInfo inblock = new EI.EIInfo();




          

         
           



            //MOVE_STOCK_NO 必须为空,不为空时，则表示修改，据此新增操作；
            string sql_str0 = "select ' ' MOVE_STOCK_NO , t.* from  tmm0031  t ";
            sql_str0 += "      where   MOVE_STOCK_APPLY_NO =  '" + MOVE_STOCK_APPLY_NO + "' ";


            inblock = EF.Utility.ExecQuery(sql_str0);
            if (inblock.Tables[0].Rows.Count < 1)
            {
                outBlock.Tables["SYS"].Rows.Add(-1, "错误,挑拨通知单[" + MOVE_STOCK_APPLY_NO + "]无效或不再有效期范围内！");
                return outBlock;
            }
            if (inblock.Tables[0].Rows[0]["BILL_STATUS"].ToString().Trim() != "30" &&
                inblock.Tables[0].Rows[0]["BILL_STATUS"].ToString().Trim() != "40")
            {
                outBlock.Tables["SYS"].Rows.Add(-1, "错误,申请单号[" + MOVE_STOCK_APPLY_NO + "]状态不对，请确认调拨出库单是否确认！");
                return outBlock;
            }

            inblock.Tables[0].Rows[0]["MOVE_STOCK_APPLY_NO"]    = MOVE_STOCK_APPLY_NO;
            inblock.Tables[0].Rows[0]["MOVE_STOCK_NO"]          = MOVE_STOCK_NO;

            

            inblock.Tables[0].Rows[0]["APPLY_TIME"] = DateTime.Now.ToString("yyyyMMddHHmmss");
            inblock.Tables[0].Rows[0]["MOVE_STOCK_TYPE"] = "BR";
            inblock.Tables[0].Rows[0]["BILL_STATUS"] = "10";
            inblock.Tables[0].Rows[0]["COMPANY_CODE"] = "NM";


            String[] pInfos = inblock.Tables[0].Rows[0]["STOCK_CHAR_END"].ToString().Trim().Split(':');
            inblock.Tables[0].Rows[0]["STOCK_CHAR_END"] = pInfos[0];


            inblock.Tables[0].Rows[0]["OLD_STOCK_NO"]   = OLD_STOCK_NO;
            inblock.Tables[0].Rows[0]["NEW_STOCK_NO"]   = NEW_STOCK_NO;

            inblock.Tables[0].Rows[0]["VEHICLE_NO"]     = VEHICLE_NO;

             






            //inblock.Tables[0].Rows[0]["OLD_STOCK_NO"] = OLD_STOCK_NO;
            //inblock.Tables[0].Rows[0]["NEW_STOCK_NO"] = NEW_STOCK_NO;
            //inblock.Tables[0].Rows[0]["MOVE_STOCK_NO"] = MOVE_STOCK_NO;



            //if (inblock.Tables[0].Rows[0]["STOCK_CHAR_END"].ToString().Trim() == "")
            //{
            //    string sql_temp = "    select CODE || ':' || CODE_DESC_1_CONTENT  as TT";
            //    sql_temp += "    from tep0002    ";
            //    sql_temp += "    where CODE_CLASS = 'MM59'   ";
            //    sql_temp += "    AND CODE IN ";
            //    sql_temp += "    (select STOCK_CHAR  from tsimm01 ";
            //    sql_temp += "    where stock_no = '" + inblock.Tables[0].Rows[0]["NEW_STOCK_NO"].ToString().Substring(0, 3) + "')";

            //    EI.EIInfo inblock_temp = EF.Utility.ExecQuery(sql_temp);
            //    if (inblock_temp.Tables[0].Rows.Count == 1)
            //    {
            //        inblock.Tables[0].Rows[0]["STOCK_CHAR_END"] = inblock_temp.Tables[0].Rows[0]["TT"];
            //    }
            //}

            //Decimal TOTAL_WT = 0, TOTAL_NUM = 0;
            //for (int i=0;i< table_rec.Rows.Count;i++)
            //{
            //    TOTAL_NUM = TOTAL_NUM + Decimal.Parse(table_rec.Rows[i]["MAT_NUM"].ToString());
            //    TOTAL_WT =  TOTAL_WT  + Decimal.Parse(table_rec.Rows[i]["MAT_WT"].ToString());

            //}

            //inblock.Tables[0].Rows[0]["TOTAL_WT"] = TOTAL_WT;
            //inblock.Tables[0].Rows[0]["TOTAL_NUM"] = TOTAL_NUM;
            //inblock.Tables[0].Rows[0]["PROPOSER"] = USERID;




            inblock.Tables.Add("TMM0033");
            inblock.Tables["TMM0033"].Merge(table_rec);


             

            inblock.sys_info.company_code = "LT";
            inblock.sys_info.company_name = "常熟市龙腾特种钢有限公司";

            inblock.sys_info.userid = USERID;
            inblock.sys_info.username = USERNAME;
            inblock.sys_info.formname = FORMNAME;



            // 调用后台services保存信息 //调拨出库；
            EI.EIInfo outBlock2 = EI.EITuxedo.CallService("mm0034_save", inblock);
            if (outBlock2.sys_info.flag != 0)
            {
                outBlock.Tables["SYS"].Rows.Add(outBlock2.sys_info.flag, outBlock2.sys_info.msg);
                return outBlock;
            }
            else
            {
                outBlock2.Tables[0].TableName = "Table0";
                outBlock.Tables.Add(outBlock2.Tables[0].Copy());
                outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, "调拨入库成功!入库单号[" + outBlock2.DataSet.Tables[0].Rows[0]["MOVE_STOCK_NO"].ToString() + "]");
                return outBlock;
            }
            

        }



        //调拨确认PA31(19->31);确认回退PB31（31->19);DEL
        [HttpPost]
        [Route("PostYm03dbi_pro")]
        public System.Data.DataSet PostYm03dbi_pro([FromBody]  JObject obj)
        {

            //系统信息；
            EI.EIInfo outBlock = new EI.EIInfo();
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");

             

        
            string MOVE_STOCK_NO = obj["MOVE_STOCK_NO"] == null ? "" : obj["MOVE_STOCK_NO"].ToString();
            string pro_type = obj["PRO_TYPE"] == null ? " " : obj["PRO_TYPE"].ToString();






            string USERID = obj["USERID"] == null ? " " : obj["USERID"].ToString();
            string USERNAME = obj["USERNAME"] == null ? " " : obj["USERNAME"].ToString();
            string FORMNAME = obj["FORMNAME"] == null ? " " : obj["FORMNAME"].ToString();
         
             


            EI.EIInfo inblock = new EI.EIInfo();


            inblock.Tables[0].Columns.Add("MOVE_STOCK_NO");
            inblock.Tables[0].Rows.Add(MOVE_STOCK_NO);



         

            inblock.sys_info.company_code = "LT";
            inblock.sys_info.company_name = "常熟市龙腾特种钢有限公司";

            inblock.sys_info.userid = USERID;
            inblock.sys_info.username = USERNAME;
            inblock.sys_info.formname = FORMNAME;


            //
            inblock.Tables[0].TableName = pro_type;

            string svr = "pmmm02n_pro";

            if (pro_type.ToUpper()=="DEL") //
            {
                svr = "mm0034_del";
            }


            // 调用后台services保存信息 //调拨出库；
            EI.EIInfo outBlock2 = EI.EITuxedo.CallService(svr, inblock);
            if (outBlock2.sys_info.flag != 0)
            {
                outBlock.Tables["SYS"].Rows.Add(outBlock2.sys_info.flag, outBlock2.sys_info.msg);
                return outBlock;
            }
            else
            {
                outBlock.Tables["SYS"].Rows.Add(outBlock2.sys_info.flag, outBlock2.sys_info.msg);
                return outBlock;
            }


        }

      
        




    }
}